package com.tsingteng.cosfun.app;

import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.os.Handler;
import android.os.Process;
import android.os.StrictMode;
import android.support.multidex.MultiDex;
import android.util.Log;


import com.faceunity.beautycontrolview.FURenderer;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.constant.SpinnerStyle;
import com.scwang.smartrefresh.layout.header.ClassicsHeader;
import com.squareup.leakcanary.LeakCanary;
import com.tencent.bugly.Bugly;
import com.tsingteng.cosfun.BuildConfig;
import com.tsingteng.cosfun.R;
import com.tsingteng.cosfun.base.UmengNotificationService;
import com.tsingteng.cosfun.common.Config;
import com.tsingteng.cosfun.crashUtils.CrashHandler;
import com.tsingteng.cosfun.http.RxRetrofit;
import com.tsingteng.cosfun.utils.CookieUtils;
import com.tsingteng.cosfun.utils.FileUtil;
import com.tsingteng.cosfun.utils.SPUtils;
import com.umeng.commonsdk.UMConfigure;
import com.umeng.message.IUmengRegisterCallback;
import com.umeng.message.MsgConstant;
import com.umeng.message.PushAgent;
import com.umeng.message.UmengNotificationClickHandler;
import com.umeng.message.entity.UMessage;
import com.umeng.socialize.PlatformConfig;
import com.umeng.socialize.UMShareAPI;

import org.litepal.LitePalApplication;
import org.litepal.tablemanager.Connector;



/**
 * 描述:全局Application
 * 创建人: 肖利
 * 时间: 2018/7/30
 * qq: (872179966)
 */
public class App extends LitePalApplication {
    private static String token;
    private static Handler handler;
    private static int mainId;

    {
        PlatformConfig.setWeixin("wx2a35bff95934a68c", "383a75493e47746657fad1fe9d1affa4");
        PlatformConfig.setQQZone("1107468920", "xTqTQwWlwOLs7DvZ");
        PlatformConfig.setSinaWeibo("1041979512", "d3812ca7104fdb2150359f1aee033086", "http://47.93.254.160/sv1/auth/callback");
    }

    @Override
    public void onCreate() {
        super.onCreate();
        AppContext.initAppContext(this);
        FURenderer.initFURenderer(this);
        UMShareAPI.get(this);//初始化sd
        UMConfigure.setLogEnabled(true);
//        LoadedApkHuaWei.hookHuaWeiVerifier(this);
        //初始化网络框架
        RxRetrofit.getInstance().initRxRetrofit(getApplicationContext(), AppContext.BASE_URL);
        //初始化缓存
        CookieUtils.init(getApplicationContext());
        //设置全局的Header构建器
        initSmartRefres();

        //初始化数据库
        initDB();

        //创建app主目录
        FileUtil.checkFileDirectory();
        //初始化推送
        initPush();
        initLeakCanary();

        //全局捕获异常
        CrashHandler.getInstance().init(this);

        //登录上报SP存储
        initLogonAndReport();
        // android 7.0系统解决拍照的问题
        StrictMode.VmPolicy.Builder builder = new StrictMode.VmPolicy.Builder();
        StrictMode.setVmPolicy(builder.build());
        builder.detectFileUriExposure();

        //初始化腾讯bugly
        Bugly.init(getApplicationContext(), BuildConfig.DEBUG ? Config.BUGLY_ID_DEBUG : Config.BUGLY_ID, false);
        //初始化handler
        handler = new Handler();
        //主线程的id
        mainId = Process.myTid();
    }

    private void initLogonAndReport() {
        if (SPUtils.init().getInt("isLoginCount") == 0) {
            SPUtils.init().putInt("isLoginCount", 2);
        }

    }




    @Override
    protected void attachBaseContext(Context base) {
        super.attachBaseContext(base);
        MultiDex.install(base);
    }


    private void initSmartRefres() {
        SmartRefreshLayout.setDefaultRefreshHeaderCreator((context, layout) -> {
            layout.setPrimaryColorsId(R.color.colorPrimary, android.R.color.white);//全局设置主题颜色
            return new ClassicsHeader(context).setSpinnerStyle(SpinnerStyle.Translate);//指定为经典Header，默认是 贝塞尔雷达Header
        });
    }

    private void initDB() {
        SQLiteDatabase db = Connector.getDatabase();
    }


    private void initPush() {
        UMConfigure.init(getApplicationContext(), UMConfigure.DEVICE_TYPE_PHONE, "5562d065d861ee329a6b3cfc9604dcbd");
        PushAgent mPushAgent = PushAgent.getInstance(this);
        mPushAgent.setResourcePackageName("com.example.tuisong");
        mPushAgent.register(new IUmengRegisterCallback() {
            @Override
            public void onSuccess(String deviceToken) {
                Log.e("获取token成功:", deviceToken);
                token = deviceToken;
//                AppListener.getInstance().getOnUmTokenListener().onGetUmToken(token);
//                AppUtils.setGid(token);
//                AppContext.init();
            }

            @Override
            public void onFailure(String s, String s1) {
                Log.e("获取token失败:", s + "且s1=" + s1);
            }
        });

        mPushAgent.setNotificationPlaySound(MsgConstant.NOTIFICATION_PLAY_SERVER); //声音
        mPushAgent.setNotificationPlayLights(MsgConstant.NOTIFICATION_PLAY_SERVER);//呼吸灯
        mPushAgent.setNotificationPlayVibrate(MsgConstant.NOTIFICATION_PLAY_SERVER);//振动

        String registrationId = mPushAgent.getRegistrationId();

        Log.e("TAG", registrationId);

        UmengNotificationClickHandler notificationClickHandler = new UmengNotificationClickHandler() {
            @Override
            public void dealWithCustomAction(Context context, UMessage msg) {

                Log.e("TAG", "-------1--------" + msg.text + "--" + msg.title);

                Log.e("TAG", "------2---------" + msg.custom);
//                Toast.makeText(context, msg.text+"--"+msg.title, Toast.LENGTH_LONG).show();
                Log.e("通知", msg.text + "--" + msg.title);
            }
        };


        mPushAgent.setPushIntentServiceClass(UmengNotificationService.class);
        mPushAgent.setNotificationClickHandler(notificationClickHandler);

    }

    /**
     * 获取友盟唯一标识
     */
    public static String getDeviceToken() {
        return token;
    }


    /**
     * 初始化内存泄漏检测
     */
    private void initLeakCanary() {
        if (LeakCanary.isInAnalyzerProcess(this)) {
            return;
        }
        LeakCanary.install(this);
    }

    /**
     * 得到全局的handler
     * @return
     */
    public static Handler getAppHanler() {
        return handler;
    }

    /**
     * 获取主线程id
     * @return
     */
    public static int getMainThreadId() {
        return mainId;
    }


}
